package com.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.entity.Asset;
import com.project.entity.AssetAllocate;
import com.project.entity.AssetFix;
import com.project.entity.AssetType;
import com.project.service.AssetAllocateService;
import com.project.service.AssetFixService;
import com.project.service.AssetService;
import com.project.service.AssetTypeService;
import com.project.util.*;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

/**
 * 资产设备控制器
 *
 * @author Leo高洋
 * @create 2023-01-17 2:32
 */
@RestController
@RequestMapping("/asset")
public class AssetController {
    @Autowired
    private AssetService assetService;

    @Autowired
    private AssetTypeService assetTypeService;

    @Autowired
    private AssetFixService assetFixService;

    @Autowired
    private AssetAllocateService assetAllocateService;

    @Value("${contractPdfFilePath}")
    private String contractPdfFilePath;

    private final static Logger logger = LoggerFactory.getLogger(AssetController.class);

    /**
     * 分页查询公共方法
     *
     * @author Leo高洋
     * @create 2023-03-16 15:51
     */
    private R getR(Map<String, Object> map) {
        List<Asset> assetsList = assetService.list(map);
        long total = assetService.getTotal(map);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("assetList", assetsList);
        resultMap.put("total", total);
        return R.ok(resultMap);
    }

    /**
     * 动态多条件分页查询资产设备
     *
     * @author Leo高洋
     * @create 2023-04-03 6:57
     */
    @PostMapping("/list")
    public R assetListByMap(@RequestBody PageBeans pageBeans) {
        logger.info("动态多条件分页查询资产设备");
        // 前端传回的参数集
        Map<String, Object> map = pageBeans.getMap();
        map.put("start", pageBeans.getStart());
        map.put("pageSize", pageBeans.getPageSize());
        System.out.println(map);
        return getR(map);
    }

    /**
     * 查寻全部资产设备信息
     *
     * @author Leo高洋
     * @create 2023-01-17 19:14
     */
    @GetMapping("/listAll")
    public R assetListAll() {
        logger.info("全部资产设备信息");
        List<Asset> assetsAllList = assetService.listAll();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("assetsAllList", assetsAllList);
        return R.ok(resultMap);
    }

    /**
     * 根据id查询资产集合
     *
     * @author Leo高洋
     * @create 2023-04-05 0:14
     */
    @PostMapping("listById")
    public R assetListById(@RequestBody Integer[] ids) {
        logger.info("根据id查询资产集合");
        List<Asset> assetList = new ArrayList<>();
        Map<String, Object> resultMap = new HashMap<>();
        for (Integer id : ids) {
            Asset asset = assetService.getById(id);
            assetList.add(asset);
        }
        resultMap.put("assetList", assetList);
        return R.ok(resultMap);
    }

    /**
     * 上传采购合同PDF
     *
     * @author Leo高洋
     * @create 2023-01-20 6:51
     */
    @PostMapping("/uploadContract")
    public R uploadContract(@RequestParam MultipartFile file) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        if (!file.isEmpty()) {
            logger.info("上传采购合同PDF");
            // 上传合同
            // 获取文件名称
            String originalFilename = file.getOriginalFilename();
            // 获取前缀
            String fileName = originalFilename.substring(0, originalFilename.indexOf("."));
            // 获取后缀
            String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 根据上传时间重新命名合同
            String newFileName = fileName + "-" + DateUtil.getCurrentDatePath() + suffixName;
            // 根据定义的位置存入合同
            FileUtils.copyInputStreamToFile(
                    file.getInputStream(), new File(contractPdfFilePath + newFileName)
            );
            resultMap.put("title", newFileName);
        }
        return R.ok(resultMap);
    }

    /**
     * 批量上传采购合同
     *
     * @author Leo高洋
     * @create 2023-04-03 2:16
     */
    @PostMapping("/uploadContractBatch")
    public R uploadContract(@RequestParam MultipartFile[] files) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        logger.info("批量上传采购合同PDF");
        for (MultipartFile file : files) {
            String originalFilename = file.getOriginalFilename();// 获取文件名称
            String fileName = originalFilename.substring(0, originalFilename.indexOf("."));// 获取前缀
            String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));// 获取后缀
            String newFileName = fileName + "-" + DateUtil.getCurrentDatePath() + suffixName;// 根据上传时间重新命名合同
            // 根据定义的位置存入合同
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(contractPdfFilePath + newFileName));
            resultMap.put("title", newFileName);
        }
        return R.ok(resultMap);
    }

    /**
     * 添加资产或者修改资产信息
     */
    @PostMapping("/save")
    public R save(@RequestBody Asset asset) {
        if (asset.getId() == null || asset.getId() == -1) {
            logger.info("添加资产数据");
            // 定义资产编号，档案馆缩写DAG拼接UUID随机五位字符串
            String zcbh = "DAG" + UUID.randomUUID().toString().substring(0, 5);
            asset.setZcbh(zcbh);
            // 设置入库时间
            asset.setRksj(new Date());
            asset.setKcsl(asset.getZcsl());
            asset.setSts(1);
            assetService.save(asset);// mybatis-plus
        } else {
            logger.info("修改资产数据");
            assetService.saveOrUpdate(asset);// mybatis-plus
        }
        return R.ok();
    }

    /**
     * 单个录入根据资产名称添加合同名称
     *
     * @author Leo高洋
     * @create 2023-04-03 2:17
     */
    @PostMapping("/saveByName")
    public R saveByName(@RequestBody Asset asset) {
        logger.info("单个录入根据资产名称添加合同名称");
        Asset assetRes = assetService.findByName(asset.getZcmc());
        assetRes.setCght(asset.getCght());
        assetService.update(assetRes, new QueryWrapper<Asset>().eq("zcmc", assetRes.getZcmc()));
        return R.ok();
    }

    /**
     * 批量添加资产数据
     *
     * @author Leo高洋
     * @create 2023-03-16 15:50
     */
    @PostMapping("/batchSave")
    public R batchSave(@RequestBody List<Asset> list) {
        logger.info("批量添加资产数据");
        for (Asset asset : list) {
            if (asset.getId() == null || asset.getId() == -1) {
                asset.setRksj(new Date());
                String zcbh = "DAG" + UUID.randomUUID().toString().substring(0, 5);
                asset.setZcbh(zcbh);
                System.out.println(asset.getName());
                AssetType assetType = assetTypeService.findByName(asset.getName());
                asset.setTypeId(assetType.getId());
                asset.setKcsl(asset.getZcsl());
                asset.setSts(1);
                assetService.save(asset);
            } else {
                assetService.saveOrUpdate(asset);
            }
        }
        return R.ok();
    }

    /**
     * 批量添加合同数据
     *
     * @author Leo高洋
     * @create 2023-04-03 2:17
     */
    @PostMapping("/batchSaveByName")
    public R batchSaveByName(@RequestBody List<Asset> list) {
        logger.info("批量添加合同数据");
        for (Asset asset : list) {
            Asset assetRes = assetService.findByName(asset.getZcmc());
            assetRes.setCght(asset.getCght());
            assetService.update(assetRes, new QueryWrapper<Asset>().eq("zcmc", assetRes.getZcmc()));
        }
        return R.ok();
    }

    /**
     * 根据id回显数据
     *
     * @author Leo高洋
     * @create 2023-03-16 15:50
     */
    @GetMapping("/{id}")
    public R findById(@PathVariable(value = "id") Integer id) {
        logger.info("根据id回显数据");
        Asset asset = assetService.getById(id);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("asset", asset);
        return R.ok(resultMap);
    }

    /**
     * 根据id查看资产的全部信息
     *
     * @author Leo高洋
     * @create 2023-03-16 15:50
     */
    @GetMapping("/info/{id}")
    public R getInfoById(@PathVariable(value = "id") Integer id) {
        logger.info("根据id查看资产的全部信息");
        List<Asset> assetList = assetService.list(new QueryWrapper<Asset>().eq("id", id));
        for (Asset asset : assetList) {
            AssetType assetType = assetTypeService.findById(String.valueOf(asset.getTypeId()));
            asset.setAssetType2(assetType);
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("assetList", assetList);
        return R.ok(resultMap);
    }

    /**
     * 删除资产数据
     *
     * @author Leo高洋
     * @create 2023-01-19 1:52
     */
    @PostMapping("/delete/{id}")
    public R delete(@PathVariable(value = "id") Integer id) {
        logger.info("删除资产数据");
        AssetFix assetFix = assetFixService.getOne(new QueryWrapper<AssetFix>().eq("assetId", id));
        AssetAllocate assetAllocate = assetAllocateService.getOne(new QueryWrapper<AssetAllocate>().eq("assetId", id));
        if (assetFix != null) {
            return R.error("当前资产正在进行维修操作，删除失败");
        } else if (assetAllocate != null) {
            System.out.println(assetAllocate);
            return R.error("当前资产已调拨，删除失败");
        } else {
            boolean b = assetService.removeById(id);
            if (b) {
                return R.ok();
            } else {
                return R.error();
            }
        }
    }

    /**
     * 根据字段名和排序串进行排序
     *
     * @author Leo高洋
     * @create 2023-03-15 15:04
     */
    @PostMapping("/sort")
    public R sort(@RequestBody SortBean sortBean) {
        logger.info("根据字段名和排序串进行排序");
        Map<String, Object> map = new HashMap<>();
        if (sortBean.getColumn() != null && !sortBean.getColumn().trim().equals("")) {
            map.put("column", sortBean.getColumn().trim());
        }
        if (sortBean.getOrder() != null && !sortBean.getOrder().trim().equals("")) {
            if (Objects.equals(sortBean.getOrder(), "ascending")) {
                sortBean.setOrder("asc");
                map.put("order", sortBean.getOrder().trim());
            } else if (Objects.equals(sortBean.getOrder(), "descending")) {
                sortBean.setOrder("desc");
                map.put("order", sortBean.getOrder().trim());
            }
        }
        map.put("start", sortBean.getStart());
        map.put("pageSize", sortBean.getPageSize());
        return getR(map);
    }
}
